// 自动保存服务
// 添加文件自动保存功能和会话恢复机制，确保数据安全和用户体验

import { invoke } from '@tauri-apps/api/core';
import { useTabStore, Tab, TabStatus } from '../stores/tabStore';

// 自动保存配置
export interface AutoSaveConfig {
  enabled: boolean;              // 是否启用自动保存
  interval: number;              // 自动保存间隔（毫秒）
  saveOnFocusLoss: boolean;      // 失去焦点时保存
  saveOnTabSwitch: boolean;      // 切换标签页时保存
  maxBackups: number;            // 最大备份数量
  backupInterval: number;        // 备份间隔（毫秒）
  sessionRecovery: boolean;      // 是否启用会话恢复
}

// 默认配置
const DEFAULT_CONFIG: AutoSaveConfig = {
  enabled: true,
  interval: 30000, // 30秒
  saveOnFocusLoss: true,
  saveOnTabSwitch: true,
  maxBackups: 5,
  backupInterval: 300000, // 5分钟
  sessionRecovery: true,
};

// 备份信息
interface BackupInfo {
  id: string;
  tabId: string;
  filePath: string;
  content: string;
  timestamp: number;
  version: number;
}

// 会话信息
interface SessionInfo {
  id: string;
  timestamp: number;
  tabs: Tab[];
  activeTabId: string | null;
  workspacePath: string;
}

// 自动保存服务类
export class AutoSaveService {
  private config: AutoSaveConfig;
  private saveTimer: NodeJS.Timeout | null = null;
  private backupTimer: NodeJS.Timeout | null = null;
  private backups = new Map<string, BackupInfo[]>();
  private isEnabled = false;
  private lastSaveTime = new Map<string, number>();

  constructor(config: Partial<AutoSaveConfig> = {}) {
    this.config = { ...DEFAULT_CONFIG, ...config };
  }

  // 启动自动保存服务
  start(): void {
    if (this.isEnabled) return;

    this.isEnabled = true;

    if (this.config.enabled) {
      this.startAutoSave();
      this.startAutoBackup();
      this.setupEventListeners();
    }

    // 恢复会话
    if (this.config.sessionRecovery) {
      this.recoverSession();
    }
  }

  // 停止自动保存服务
  stop(): void {
    if (!this.isEnabled) return;

    this.isEnabled = false;
    this.stopAutoSave();
    this.stopAutoBackup();
    this.removeEventListeners();
  }

  // 启动自动保存定时器
  private startAutoSave(): void {
    if (this.saveTimer) return;

    this.saveTimer = setInterval(() => {
      this.performAutoSave();
    }, this.config.interval);
  }

  // 停止自动保存定时器
  private stopAutoSave(): void {
    if (this.saveTimer) {
      clearInterval(this.saveTimer);
      this.saveTimer = null;
    }
  }

  // 启动自动备份定时器
  private startAutoBackup(): void {
    if (this.backupTimer) return;

    this.backupTimer = setInterval(() => {
      this.performAutoBackup();
    }, this.config.backupInterval);
  }

  // 停止自动备份定时器
  private stopAutoBackup(): void {
    if (this.backupTimer) {
      clearInterval(this.backupTimer);
      this.backupTimer = null;
    }
  }

  // 执行自动保存
  private async performAutoSave(): Promise<void> {
    const tabStore = useTabStore.getState();
    const modifiedTabs = tabStore.getModifiedTabs();

    for (const tab of modifiedTabs) {
      const lastSave = this.lastSaveTime.get(tab.id) || 0;
      const now = Date.now();

      // 检查是否需要保存（避免频繁保存）
      if (now - lastSave >= this.config.interval) {
        await this.saveTab(tab);
        this.lastSaveTime.set(tab.id, now);
      }
    }
  }

  // 执行自动备份
  private async performAutoBackup(): Promise<void> {
    const tabStore = useTabStore.getState();
    const allTabs = Array.from(tabStore.tabs.values());

    for (const tab of allTabs) {
      if (tab.status === TabStatus.Modified || tab.status === TabStatus.New) {
        await this.createBackup(tab);
      }
    }
  }

  // 保存标签页
  private async saveTab(tab: Tab): Promise<boolean> {
    try {
      // 更新状态为保存中
      const tabStore = useTabStore.getState();
      tabStore.updateTabStatus(tab.id, TabStatus.Saving);

      // 调用Tauri API保存文件
      await invoke('write_file_content', {
        path: tab.filePath,
        content: tab.content,
      });

      // 更新状态为已保存
      tabStore.updateTabStatus(tab.id, TabStatus.Clean);
      
      console.log(`Auto-saved: ${tab.filePath}`);
      return true;
    } catch (error) {
      console.error(`Failed to auto-save ${tab.filePath}:`, error);
      
      // 更新状态为错误
      const tabStore = useTabStore.getState();
      tabStore.updateTabStatus(tab.id, TabStatus.Error);
      
      return false;
    }
  }

  // 创建备份
  private async createBackup(tab: Tab): Promise<void> {
    const backupId = `backup_${tab.id}_${Date.now()}`;
    const backup: BackupInfo = {
      id: backupId,
      tabId: tab.id,
      filePath: tab.filePath,
      content: tab.content,
      timestamp: Date.now(),
      version: this.getNextBackupVersion(tab.id),
    };

    // 获取或创建备份列表
    let tabBackups = this.backups.get(tab.id) || [];
    
    // 添加新备份
    tabBackups.push(backup);
    
    // 限制备份数量
    if (tabBackups.length > this.config.maxBackups) {
      tabBackups = tabBackups.slice(-this.config.maxBackups);
    }
    
    this.backups.set(tab.id, tabBackups);

    // 保存备份到本地存储
    try {
      localStorage.setItem(`backup_${tab.id}`, JSON.stringify(tabBackups));
    } catch (error) {
      console.error('Failed to save backup to localStorage:', error);
    }
  }

  // 获取下一个备份版本号
  private getNextBackupVersion(tabId: string): number {
    const tabBackups = this.backups.get(tabId) || [];
    if (tabBackups.length === 0) return 1;
    
    const lastBackup = tabBackups[tabBackups.length - 1];
    return lastBackup.version + 1;
  }

  // 恢复备份
  async restoreBackup(tabId: string, backupId: string): Promise<boolean> {
    const tabBackups = this.backups.get(tabId);
    if (!tabBackups) return false;

    const backup = tabBackups.find(b => b.id === backupId);
    if (!backup) return false;

    try {
      const tabStore = useTabStore.getState();
      tabStore.updateTabContent(tabId, backup.content);
      
      console.log(`Restored backup for tab ${tabId}: ${backup.id}`);
      return true;
    } catch (error) {
      console.error('Failed to restore backup:', error);
      return false;
    }
  }

  // 获取标签页的备份列表
  getBackups(tabId: string): BackupInfo[] {
    return this.backups.get(tabId) || [];
  }

  // 清理旧备份
  cleanupOldBackups(): void {
    const cutoffTime = Date.now() - (7 * 24 * 60 * 60 * 1000); // 7天前

    this.backups.forEach((tabBackups, tabId) => {
      const filteredBackups = tabBackups.filter(backup => backup.timestamp > cutoffTime);
      
      if (filteredBackups.length !== tabBackups.length) {
        this.backups.set(tabId, filteredBackups);
        
        try {
          localStorage.setItem(`backup_${tabId}`, JSON.stringify(filteredBackups));
        } catch (error) {
          console.error('Failed to update backup in localStorage:', error);
        }
      }
    });
  }

  // 保存会话
  async saveSession(): Promise<void> {
    if (!this.config.sessionRecovery) return;

    try {
      const tabStore = useTabStore.getState();
      const session: SessionInfo = {
        id: `session_${Date.now()}`,
        timestamp: Date.now(),
        tabs: Array.from(tabStore.tabs.values()),
        activeTabId: tabStore.activeTabId,
        workspacePath: '', // 这里应该从某个地方获取工作区路径
      };

      localStorage.setItem('editor_session', JSON.stringify(session));
      console.log('Session saved');
    } catch (error) {
      console.error('Failed to save session:', error);
    }
  }

  // 恢复会话
  async recoverSession(): Promise<boolean> {
    if (!this.config.sessionRecovery) return false;

    try {
      const sessionData = localStorage.getItem('editor_session');
      if (!sessionData) return false;

      const session: SessionInfo = JSON.parse(sessionData);
      const tabStore = useTabStore.getState();

      // 恢复标签页
      for (const tab of session.tabs) {
        await tabStore.openTab(tab.filePath, tab.content, {
          ...tab,
          id: tab.id, // 保持原有ID
        });
      }

      // 恢复活动标签页
      if (session.activeTabId) {
        tabStore.activateTab(session.activeTabId);
      }

      console.log(`Session recovered: ${session.tabs.length} tabs`);
      return true;
    } catch (error) {
      console.error('Failed to recover session:', error);
      return false;
    }
  }

  // 清除会话
  clearSession(): void {
    try {
      localStorage.removeItem('editor_session');
      console.log('Session cleared');
    } catch (error) {
      console.error('Failed to clear session:', error);
    }
  }

  // 设置事件监听器
  private setupEventListeners(): void {
    // 窗口失去焦点时保存
    if (this.config.saveOnFocusLoss) {
      window.addEventListener('blur', this.handleFocusLoss);
    }

    // 页面卸载前保存会话
    window.addEventListener('beforeunload', this.handleBeforeUnload);

    // 监听标签页切换
    if (this.config.saveOnTabSwitch) {
      // 这里应该监听标签页切换事件
      // 由于useTabStore是Zustand store，可以通过subscribe监听
    }
  }

  // 移除事件监听器
  private removeEventListeners(): void {
    window.removeEventListener('blur', this.handleFocusLoss);
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }

  // 处理焦点丢失
  private handleFocusLoss = (): void => {
    if (this.config.saveOnFocusLoss) {
      this.performAutoSave();
    }
  };

  // 处理页面卸载前
  private handleBeforeUnload = (): void => {
    this.saveSession();
  };

  // 更新配置
  updateConfig(newConfig: Partial<AutoSaveConfig>): void {
    const oldEnabled = this.config.enabled;
    this.config = { ...this.config, ...newConfig };

    // 如果启用状态改变，重新启动或停止服务
    if (oldEnabled !== this.config.enabled) {
      if (this.config.enabled) {
        this.startAutoSave();
        this.startAutoBackup();
      } else {
        this.stopAutoSave();
        this.stopAutoBackup();
      }
    } else if (this.config.enabled) {
      // 如果间隔时间改变，重新启动定时器
      this.stopAutoSave();
      this.stopAutoBackup();
      this.startAutoSave();
      this.startAutoBackup();
    }
  }

  // 获取配置
  getConfig(): AutoSaveConfig {
    return { ...this.config };
  }
}

// 单例实例
let autoSaveService: AutoSaveService | null = null;

// 获取自动保存服务实例
export const getAutoSaveService = (config?: Partial<AutoSaveConfig>): AutoSaveService => {
  if (!autoSaveService) {
    autoSaveService = new AutoSaveService(config);
  }
  return autoSaveService;
};

// 重置自动保存服务
export const resetAutoSaveService = (): void => {
  if (autoSaveService) {
    autoSaveService.stop();
    autoSaveService = null;
  }
};
